<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="90px">
      <!--<el-form-item label="外部商户号" prop="outMerchantNo">-->
      <!--  <el-input v-model="queryParams.outMerchantNo" placeholder="请输入外部商户号" clearable @keyup.enter="handleQuery" />-->
      <!--</el-form-item>-->
      <el-form-item label="外部终端号" prop="outTerminalNo">
        <el-input v-model="queryParams.outTerminalNo" clearable placeholder="请输入外部终端号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="签购单名称" prop="terminalName">
        <el-input v-model="queryParams.terminalName" clearable placeholder="请输入签购单名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="设备号" prop="deviceSn">
        <el-input v-model="queryParams.deviceSn" clearable placeholder="请输入设备号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactTel">
        <el-input v-model="queryParams.contactTel" clearable placeholder="请输入联系电话" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:terminal:add']" icon="Plus" plain type="primary" @click="handleAdd">新增 </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:terminal:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate">修改 </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-row style="margin-bottom: 10px; margin-top: 10px">
      <el-alert :closable="false" class="mb20" show-icon title="温馨提示:只有绑定了设备的终端才可以交易" type="success" />
    </el-row>

    <el-table v-loading="loading" :data="terminalList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="外部商户号" prop="outMerchantNo" width="180" />
      <el-table-column align="center" label="外部终端号" prop="outTerminalNo" width="150" />
      <el-table-column align="center" label="外部设备号" prop="outDeviceSn" width="150">
        <template #default="scope">
          <span v-if="scope.row.outDeviceSn != null">
            {{ scope.row.outDeviceSn }}
          </span>
          <span v-else> ---- </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备类型" prop="deviceType" width="100">
        <template #default="scope">
          <span v-if="scope.row.deviceType">
            {{ parseDeviceType(scope.row.deviceType) }}
          </span>
          <span v-else> ---- </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="签购单名称" prop="terminalName" width="100" />
      <el-table-column align="center" label="码牌展示名称" prop="merchantCodeName" width="200" />
      <el-table-column align="center" label="设备号" prop="deviceSn" width="100" />
      <el-table-column align="center" label="外部设备号" prop="outDeviceSn" width="150" />
      <el-table-column align="center" label="联系电话" prop="contactTel" width="130" />

      <el-table-column align="center" width="200">
        <template #header>
          <p>地址</p>
          <p>安装地址</p>
        </template>
        <template #default="scope">
          <p> {{ scope.row.installProvinceShow }}/ {{ scope.row.installCityShow }} / {{ scope.row.installDistrictShow }} </p>
          <p>
            {{ scope.row.installAddress }}
          </p>
        </template>
      </el-table-column>

      <el-table-column align="center" label="查询" prop="isOpenConsume">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenConsume" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="退货" prop="isOpenRefund">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenRefund" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="消费类" prop="isOpenQueryTrade">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenQueryTrade" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="预授权类" prop="isOpenPreauthorize">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPreauthorize" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="借记卡" prop="isOpenDebitCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenDebitCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="贷记卡" prop="isOpenCreditCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenCreditCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="准贷记卡" prop="isOpenSemiCreditCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenSemiCreditCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="预付费卡" prop="isOpenPrepaidCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPrepaidCard" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="二维码预授权类" prop="isOpenPrepaidCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPreauthorizeQr" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="审核状态" prop="auditStatus">
        <template #default="scope">
          <dict-tag :options="audit_status" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="商户状态" prop="merchantStatus">
        <template #default="scope">
          <dict-tag :options="merchant_terminal_status" :value="scope.row.terminalStatus" />
        </template>
      </el-table-column>

      <el-table-column :fixed="'right'" align="center" class-name="small-padding fixed-width" label="操作" width="340">
        <template #default="scope">
          <el-button v-hasPermi="['laiqianle:terminal:edit']" icon="Edit" type="text" @click="handleUpdate(scope.row)"> 修改 </el-button>
          <!--                    <el-button icon="upload" type="text" @click="handleReport(scope.row)">上报机构</el-button>-->
          <el-button type="text" @click="handleBind(scope.row, true)">绑定设备</el-button>
          <el-button type="text" @click="handleUnBind(scope.row)">解绑设备</el-button>
          <el-button icon="View" type="text" @click="shwoQrcodeHandle(scope.row)">查看码牌</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    <!-- 添加或修改来钱乐终端对话框 -->
    <el-drawer v-model="open" :title="title" append-to-body size="45%">
      <el-alert title="码牌展示名称最多输入13个字符" :closable="false" type="success" />

      <el-divider />

      <el-form ref="terminalRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="码牌展示名称" prop="merchantCodeName">
          <el-input v-model="form.merchantCodeName" maxlength="13" show-word-limit placeholder="码牌展示名称" />
        </el-form-item>
        <!-- <el-row> -->
        <el-form-item label="设备类型" prop="deviceType">
          <el-radio-group v-model="form.deviceType" @change="changeDeviceType">
            <el-radio :label="1">钱宝</el-radio>
            <el-radio :label="2">兴业</el-radio>
            <el-radio :label="3">邮储</el-radio>
            <el-radio :label="4">N7</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- </el-row> -->
        <el-form-item label="设备号" v-if="!editFlag || showTerNum">
          <el-select
            v-model="form.deviceSn"
            style="width: 100%"
            :loading="loading1"
            :remote-method="remoteMethod"
            filterable
            placeholder="请输入设备号选择绑定设备"
            remote
            remote-show-suffix
            reserve-keyword
          >
            <el-option v-for="item in deviceList" :key="item.sn" :label="item.sn" :value="item.sn" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showN7TerNum" :rules="[{ required: true, message: 'N7设备号不能为空', trigger: 'blur' }]" label="N7设备号" prop="nsn">
          <el-input v-model="form.nsn" placeholder="请输入N7设备号" />
        </el-form-item>
        <el-form-item label="签购单名称" prop="terminalName">
          <el-input v-model="form.terminalName" placeholder="请输入签购单名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactTel">
          <el-input v-model="form.contactTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="form.installAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="省市区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="installProvince">
                <el-select v-model="form.installProvince" :clearable="true" placeholder="请选择省" @change="handleProvinceChange">
                  <el-option v-for="item1 in provinceOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installCity">
                <el-select v-model="form.installCity" :clearable="true" placeholder="请选择市" @change="handleCityChange">
                  <el-option v-for="item1 in cityOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installDistrict">
                <el-select v-model="form.installDistrict" :clearable="true" placeholder="请选择区">
                  <el-option v-for="item1 in districtOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row>
          <el-form-item label="交易权限-查询" label-width="150px" prop="isOpenConsume">
            <el-switch v-model="form.isOpenConsume" />
          </el-form-item>
          <el-form-item label="交易权限-退货" label-width="150px" prop="isOpenRefund">
            <el-switch v-model="form.isOpenRefund" />
          </el-form-item>
          <el-form-item label="交易权限-消费类" label-width="150px" prop="isOpenQueryTrade">
            <el-switch v-model="form.isOpenQueryTrade" />
          </el-form-item>
          <el-form-item label="交易权限-预授权类" label-width="150px" prop="isOpenPreauthorize">
            <el-switch v-model="form.isOpenPreauthorize" />
          </el-form-item>
          <el-form-item label="卡类型权限-借记卡" label-width="150px" prop="isOpenDebitCard">
            <el-switch v-model="form.isOpenDebitCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-贷记卡" label-width="150px" prop="isOpenCreditCard">
            <el-switch v-model="form.isOpenCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-准贷记卡" label-width="150px" prop="isOpenSemiCreditCard">
            <el-switch v-model="form.isOpenSemiCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-预付费卡" label-width="150px" prop="isOpenPrepaidCard">
            <el-switch v-model="form.isOpenPrepaidCard" />
          </el-form-item>
          <el-form-item label="交易权限-二维码预授权类" label-width="190px" prop="isOpenPreauthorizeQr">
            <el-switch v-model="form.isOpenPreauthorizeQr" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="是否强制交易备注" label-width="150px" prop="is_remarks">
            <el-radio-group v-model="form.is_remarks" class="ml-4">
              <el-radio :label="0">不强制</el-radio>
              <el-radio :label="1">强制</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-alert :closable="false" class="mb20" show-icon title="温馨提示：同地址请上传增机单,否则请上传门店照片(最多支持5张)" type="info" />
          <el-col v-for="(item1, index1) in form.fileList" :key="item1" :span="8">
            <el-form-item :label="`上传图片`" :prop="`imgList[${index1}].path`" label-width="80px">
              <ImageUpload1 v-model="item1.path" />
              <div class="img-wrap">
                <el-button v-if="index1 + 1 === form.fileList.length && form.fileList.length < 5" type="primary" @click="form.fileList.push({ path: null })">
                  添加
                </el-button>
                <el-button v-if="form.fileList.length > 1" type="danger" @click="form.fileList.splice(index1, 1)">删除 </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <el-dialog v-model="dialogFormVisible" title="绑定设备" width="30%">
      <el-select v-model="bindDevice" :loading="loading1" :remote-method="remoteMethod" filterable placeholder="请选择绑定设备" remote remote-show-suffix reserve-keyword>
        <el-option v-for="item in deviceList" :key="item.sn" :label="item.sn" :value="item.sn" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleBindCancel">取消</el-button>
          <el-button type="primary" @click="handleBindConfirm" :loading="handleBindConfirmButton">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 展示马牌 -->
    <el-dialog v-model="showQrcodeOpen" append-to-body width="600px">
      <ImagePreview v-if="showQrcode" :src="QrcodeUrl" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="downloadFile(QrcodeUrl)">下载</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Terminal" setup>
  import { ElMessage } from 'element-plus';
  import { getCurrentInstance, reactive, ref, toRefs } from 'vue';

  import { addTerminal, getTerminal, listTerminal, showQrcode, terminalBind, terminalUnBind, terUp, updateTerminal } from '@/api/laiqianle/terminal';
  import { areaListByParentId, equipmentDetail, getDeviceList } from '@/api/laiqianle/register';
  import ImageUpload1 from '../ImageUpload.vue';

  const props = defineProps({
    outMerchantNo: {
      type: String,
      default: '',
    },
  });
  const { proxy } = getCurrentInstance();

  const { sys_my_yes_no, merchant_terminal_status, audit_status } = proxy.useDict('sys_my_yes_no', 'merchant_terminal_status', 'audit_status');

  const showTerNum = ref<boolean>(true); // 是否展示设备号
  const showN7TerNum = ref<boolean>(false); // 是否展示N7设备号

  const editFlag = ref<boolean>(false);
  const terminalList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const showQrcodeOpen = ref(false);
  const QrcodeUrl = ref('');
  const terminal = ref(null);
  const isRemote = ref(true);
  const handleBindConfirmButton = ref(false);

  // 省市区
  interface provinces {
    id: number;
    name: string;
    code: string;
    pcode: string;

    [key: string]: any;
  }

  let provinceOptions = ref<provinces[]>([]);
  let cityOptions = ref<provinces[]>([]);
  let districtOptions = ref<provinces[]>([]);
  const getProvinceList = async (parentId) => {
    if (parentId === '') return [];
    const { data } = await areaListByParentId(parentId);
    return data;
  };
  provinceOptions.value = await getProvinceList(0);

  const handleProvinceChange = async (value) => {
    cityOptions.value = await getProvinceList(value);
    form.value['installCity'] = null;
    form.value['installDistrict'] = null;
  };

  // 解析设备类型
  const parseDeviceType = (type) => {
    let str = '-';
    switch (type) {
      case 1:
        str = '钱宝';
        break;
      case 2:
        str = '兴业';
        break;
      case 3:
        str = '邮储';
        break;
      case 4:
        str = 'N7';
        break;
      default:
        str = '-';
        break;
    }
    return str;
  };

  const handleCityChange = async (value) => {
    districtOptions.value = await getProvinceList(value);
    form.value['installDistrict'] = null;
  };

  const data = reactive({
    form: {} as any,
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      outMerchantNo: props.outMerchantNo,
      outTerminalNo: null,
      terminalName: null,
      deviceSn: null,
      contactTel: null,
      installAddress: null,
      installProvince: null,
      installCity: null,
      installDistrict: null,
      isOpenConsume: null,
      isOpenRefund: null,
      isOpenQueryTrade: null,
      isOpenPreauthorize: null,
      isOpenDebitCard: null,
      isOpenCreditCard: null,
      isOpenSemiCreditCard: null,
      isOpenPrepaidCard: null,
    },
    rules: {
      deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
      outMerchantNo: [{ required: true, message: '外部商户号不能为空', trigger: 'blur' }],
      outTerminalNo: [{ required: true, message: '外部终端号不能为空', trigger: 'blur' }],
      terminalName: [{ required: true, message: '签购单名称不能为空', trigger: 'blur' }],
      contactTel: [
        { required: true, message: '联系电话不能为空', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'change' },
      ],
      installAddress: [{ required: true, message: '安装地址不能为空', trigger: 'blur' }],
      installProvince: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
      installCity: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
      installDistrict: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询来钱乐终端列表 */
  function getList() {
    loading.value = true;
    listTerminal(queryParams.value).then((response) => {
      terminalList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 设备类型选择改变
  function changeDeviceType(e) {
    if (e === 1) {
      // 钱宝 不做操作
      showTerNum.value = true;
      showN7TerNum.value = false;
      form.value.nsn = null;
      title.value = '添加钱宝终端';
    } else if (e === 2 || e === 3) {
      showTerNum.value = false;
      showN7TerNum.value = false;
      form.value.nsn = null;
      form.value.deviceSn = null;
      title.value = e === 2 ? '添加兴业终端' : '添加邮储终端';
    } else if (e === 4) {
      // N7 新增nsn字段
      showTerNum.value = true;
      showN7TerNum.value = true;
      title.value = '添加N7终端';
    }
  }
  // 表单重置
  function reset() {
    form.value = {
      id: null,
      deviceType: 1,
      outMerchantNo: props.outMerchantNo,
      outTerminalNo: null,
      terminalName: null,
      deviceSn: null,
      contactTel: null,
      installAddress: null,
      installProvince: null,
      installCity: null,
      installDistrict: null,
      isOpenConsume: null,
      isOpenRefund: null,
      isOpenQueryTrade: null,
      isOpenPreauthorize: null,
      isOpenDebitCard: null,
      isOpenCreditCard: null,
      isOpenSemiCreditCard: null,
      isOpenPrepaidCard: null,
      isOpenPreauthorizeQr: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      delFlag: null,
      fileList: [{ path: null }],
    };
    showN7TerNum.value = false;
    showTerNum.value = true;
    proxy.resetForm('terminalRef');
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    editFlag.value = false;
    open.value = true;
    title.value = '添加钱宝终端';
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    editFlag.value = true;
    getTerminal(_id).then(async (response) => {
      form.value = {
        ...response.data,
        isOpenConsume: response.data.isOpenConsume === 'true',
        isOpenRefund: response.data.isOpenRefund === 'true',
        isOpenQueryTrade: response.data.isOpenQueryTrade === 'true',
        isOpenPreauthorize: response.data.isOpenPreauthorize === 'true',
        isOpenDebitCard: response.data.isOpenDebitCard === 'true',
        isOpenCreditCard: response.data.isOpenCreditCard === 'true',
        isOpenSemiCreditCard: response.data.isOpenSemiCreditCard === 'true',
        isOpenPrepaidCard: response.data.isOpenPrepaidCard === 'true',
        isOpenPreauthorizeQr: response.data.isOpenPreauthorizeQr === 'true',
        fileList: response.data.fileList && response.data.fileList.length > 0 ? response.data.fileList : [{ path: null }],
        is_remarks: Number(response.data.is_remarks),
      };

      cityOptions.value = await getProvinceList(response.data.installProvince);
      districtOptions.value = await getProvinceList(response.data.installCity);
      open.value = true;
      // title.value = '修改终端';
      if (response.data.deviceType == 1) {
        title.value = '修改钱宝终端';
      } else if (response.data.deviceType == 2) {
        title.value = '修改兴业终端';
      } else if (response.data.deviceType == 3) {
        title.value = '修改邮储终端';
      } else if (response.data.deviceType == 4) {
        title.value = '修改N7终端';
      } else {
        title.value = '修改终端';
      }
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['terminalRef'].validate((valid) => {
      if (valid) {
        form.value['fileList'] = form.value['fileList']
          .filter((item) => item.path !== null)
          .map((item, index) => ({
            ...item,
            fileTypeId: index + 101,
          }));
        // console.log('提交数据', form.value);
        // return;
        if (form.value['id'] != null) {
          delete form.value.deviceSn;
          updateTerminal(form.value).then(() => {
            proxy.$modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          if (!form.value.deviceSn) {
            delete form.value.deviceSn;
          }
          addTerminal(form.value).then(() => {
            proxy.$modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download(
      'laiqianle/terminal/export',
      {
        ...queryParams.value,
      },
      `terminal_${new Date().getTime()}.xlsx`,
    );
  }

  /** 上报机构 */
  const handleReport = (row) => {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm('是否确认上报商户注册编号为"' + _ids + '"的数据项？')
      .then(function () {
        return terUp(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('上报成功');
      })
      .catch(() => {});
  };

  const dialogFormVisible = ref(false);
  const bindDevice = ref(null);
  const terminalId = ref(null);
  const loading1 = ref(false);
  const deviceList = ref([]);
  const remoteMethod = (query: string) => {
    if (query) {
      loading1.value = true;
      getDeviceList({ sn: query }).then((res) => {
        deviceList.value = res.rows;
        loading1.value = false;
      });
    } else {
      deviceList.value = [];
    }
  };
  const handleBind = (row, isRemoteP) => {
    terminalId.value = row.outTerminalNo;
    terminal.value = row;
    dialogFormVisible.value = true;
    isRemote.value = isRemoteP;
  };

  const handleUnBind = (row) => {
    proxy.$modal
      .confirm('是否确认解绑商户注册编号为"' + row.outMerchantNo + '"的数据项？')
      .then(function () {
        return terminalUnBind(row);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('解绑成功');
      })
      .catch(() => {});
  };

  const handleBindConfirm = () => {
    equipmentDetail(bindDevice.value).then((res) => {
      if (res.data) {
        if (res.data.isBuild == 0 && res.data.isOutDevice == 1) {
          console.log(isRemote);
          terminal.value.deviceSn = bindDevice;

          handleBindConfirmButton.value = true;
          if (isRemote.value) {
            terminalBind(terminal.value)
              .then(() => {
                ElMessage.success('绑定成功');
                bindDevice.value = null;
                terminalId.value = null;
                dialogFormVisible.value = false;
                handleBindConfirmButton.value = false;
                getList();
              })
              .catch(() => {
                ElMessage.error('绑定失败');
              });
          } else {
            terminalBindLocal(terminal.value)
              .then(() => {
                ElMessage.success('绑定成功');
                bindDevice.value = null;
                terminalId.value = null;
                dialogFormVisible.value = false;
                handleBindConfirmButton.value = false;
                getList();
              })
              .catch(() => {
                ElMessage.error('绑定失败');
              });
          }
        } else {
          ElMessage.error('设备不存在或未生成');
        }
      } else {
        ElMessage.error('设备不存在');
      }
    });
  };
  const handleBindCancel = () => {
    bindDevice.value = null;
    dialogFormVisible.value = false;
  };

  /**
   * 展示码牌
   * @param row
   */
  function shwoQrcodeHandle(row) {
    showQrcode(row).then((res) => {
      if (res.data) {
        QrcodeUrl.value = '';
        showQrcodeOpen.value = true;
        QrcodeUrl.value = res.data;
      }
    });
  }

  function downloadFile(file) {
    const fi = import.meta.env.VITE_APP_BASE_API + file;
    let arr = file.split('/'); // 以 "/" 为分隔符，将字符串分割成数组
    saveAs(fi, arr[3]);
  }

  getList();
</script>
<style lang="scss" scoped>
  .mb20 {
    margin-bottom: 20px !important;
  }

  .img-wrap {
    width: 100%;
    box-sizing: border-box;
    padding-right: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
  }
</style>
